const baseInfoTemplate = `
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本信息</span>
    </div>
    <div>
    <el-form ref="form" :disabled="isDisable" label-suffix=":" :model="formData" :rules="rules" label-width="117px" size="small">
      <el-row>
        <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-input ref="name" :disabled="type === 'supplement'" v-model="formData.name" placeholder="自动识别或手动输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="身份证号" prop="idNum">
          <el-input ref="idNum" :disabled="type === 'supplement'" :maxlength="18" v-model="formData.idNum"  @change="idNoInputHandler" placeholder="自动识别或手动输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item style="height: 156px;" label="身份证正面">
        <el-upload
          action="#"
          ref="uploadFront"
          :file-list="idFrontFile"
          accept="image/*"
          :auto-upload="false"
          :limit="limitCount"
          list-type="picture-card"
          :on-change="(file, fileList) => handlePictureChange(file, fileList, 'id-front', 'uploadFront')"
          :on-preview="handlePicturePreview"
          :on-remove="(file, fileList) => handleRemove('id-front')">
          <i style="line-height: 148px;" class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">只能上传jpeg/jpg/png文件，且不超过500kb</div>
        </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item style="height: 156px;" label="身份证反面">
          <el-upload
            action="#"
            ref="uploadBack"
            accept="image/*"
            :file-list="idBackFile"
            :auto-upload="false"
            :limit="limitCount"
            list-type="picture-card"
            :on-change="(file, fileList) => handlePictureChange(file, fileList, 'id-back', 'uploadBack')"
            :on-preview="handlePicturePreview"
            :on-remove="(file, fileList) => handleRemove('id-back')">
            <i style="line-height: 148px;" class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpeg/jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="电话" prop="phone">
          <el-input :maxlength="11" v-model="formData.phone" placeholder="请输入11位手机号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="民族">
          <el-input v-model="formData.nationality" placeholder="自动识别或手动输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="性别">
          <el-select v-model="formData.gender" placeholder="请选择">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="生日">
        <el-date-picker
          style="width: 100%;"
          value-format="yyyy-MM-dd"
          v-model="formData.birthday"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="地址">
          <el-input v-model="formData.address" placeholder="自动识别或手动输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="邮箱号">
          <el-input v-model="formData.email" placeholder="请输入邮箱号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="QQ">
          <el-input v-model="formData.qq" placeholder="请输入QQ号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="工作单位">
          <el-input v-model="formData.work" placeholder="请输入工作单位"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="1寸蓝/白底照片">
          <el-upload
            action="#"
            ref="upload1Cun"
            accept="image/*"
            :file-list="cun1File"
            :auto-upload="false"
            :limit="limitCount"
            list-type="picture-card"
            :on-change="(file, fileList) => handlePictureChange(file, fileList, '1cun', 'upload1Cun')"
            :on-preview="handlePicturePreview"
            :on-remove="(file, fileList) => handleRemove('1cun')">
            <i style="line-height: 148px;" class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpeg/jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="2寸蓝/白底照片">
          <el-upload
            action="#"
            ref="upload2Cun"
            accept="image/*"
            :file-list="cun2File"
            :auto-upload="false"
            :limit="limitCount"
            list-type="picture-card"
            :on-change="(file, fileList) => handlePictureChange(file, fileList, '2cun', 'upload2Cun')"
            :on-preview="handlePicturePreview"
            :on-remove="(file, fileList) => handleRemove('2cun')">
            <i style="line-height: 148px;" class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpeg/jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-col>
      </el-row>
    </el-form>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-card>
`;

Vue.component('app-base-information', {
  name: 'app-base-information',
  template: baseInfoTemplate,
  props: ['type', 'fileMap'],
  data() {
    var validateIdNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入身份证号码'));
      } else {
        const isValid =
          /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            value
          );
        if (!isValid) {
          callback(new Error('身份证号码有误'));
        } else {
          callback();
        }
      }
    };

    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else {
        const isValid = /^1[3456789]\d{9}$/.test(value);
        if (!isValid) {
          callback(new Error('手机号码有误'));
        } else {
          callback();
        }
      }
    };

    return {
      limitCount: 1,
      dialogVisible: false,
      dialogImageUrl: '',
      fileDic: new Map(),
      formData: {
        name: '',
        idNum: '',
        phone: '',
        nationality: '',
        gender: '',
        birthday: '',
        address: '',
        email: '',
        qq: '',
        work: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
          },
        ],
        idNum: [
          {
            required: true,
            validator: validateIdNo,
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  computed: {
    isDisable() {
      return this.type === 'look';
    },
    idFrontFile() {
      const file = this.fileMap.find((item) => item.property === 'id-front');
      if (file) {
        this.$refs.uploadFront.$children[1].$el.style = 'display: none;';
        return [
          {
            name: file.property,
            url: `/apistudentInfo/picDownload?url=${encodeURIComponent(
              file.fileResource
            )}`,
          },
        ];
      } else {
        this.$nextTick(() => {
          this.$refs.uploadFront.$children[1].$el.style = 'display: block;';
        });
        return [];
      }
    },
    idBackFile() {
      const file = this.fileMap.find((item) => item.property === 'id-back');
      if (file) {
        this.$refs.uploadBack.$children[1].$el.style = 'display: none;';
        return [
          {
            name: file.property,
            url: `/apistudentInfo/picDownload?url=${encodeURIComponent(
              file.fileResource
            )}`,
          },
        ];
      } else {
        this.$nextTick(() => {
          this.$refs.uploadBack.$children[1].$el.style = 'display: block;';
        });
        return [];
      }
    },
    cun1File() {
      const file = this.fileMap.find((item) => item.property === '1cun');
      if (file) {
        this.$refs.upload1Cun.$children[1].$el.style = 'display: none;';
        return [
          {
            name: file.property,
            url: `/apistudentInfo/picDownload?url=${encodeURIComponent(
              file.fileResource
            )}`,
          },
        ];
      } else {
        this.$nextTick(() => {
          this.$refs.upload1Cun.$children[1].$el.style = 'display: block;';
        });
        return [];
      }
    },
    cun2File() {
      const file = this.fileMap.find((item) => item.property === '2cun');
      if (file) {
        this.$refs.upload2Cun.$children[1].$el.style = 'display: none;';
        return [
          {
            name: file.property,
            url: `/apistudentInfo/picDownload?url=${encodeURIComponent(
              file.fileResource
            )}`,
          },
        ];
      } else {
        this.$nextTick(() => {
          this.$refs.upload2Cun.$children[1].$el.style = 'display: block;';
        });
        return [];
      }
    },
  },
  methods: {
    idNoInputHandler(value) {
      if (this.isDisable) return;
      const isValid =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
          value
        );
      if (!isValid) return;
      this.getInfoByIdNo(value);
    },
    getInfoByIdNo(idNo) {
      $.ajax({
        url: baseUrl + 'studentInfo/getStudentInfo',
        method: 'get',
        data: { idNo },
        headers: {
          Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
        },
        success: (data) => {
          const { student, studentCards } = data;

          if (!student && !studentCards) return;

          this.formData.name = student.name;
          this.formData.idNum = student.idNo;
          this.formData.phone = student.phoneNum;
          this.formData.nationality = student.nation;
          this.formData.gender = student.sex;
          this.formData.birthday = student.birthday;
          this.formData.address = student.address;
          this.formData.email = student.email;
          this.formData.qq = student.qqNumber;
          this.formData.work = student.workAdress;

          this.$emit('on-get-info', data);
        },
      });
    },
    hideOrShowUpload(name, isShow) {
      switch (name) {
        case 'id-front':
          this.$refs.uploadFront.$children[1].$el.style = isShow
            ? ''
            : 'display: none;';
          break;
        case 'id-back':
          this.$refs.uploadBack.$children[1].$el.style = isShow
            ? ''
            : 'display: none;';
          break;
        case '1cun':
          this.$refs.upload1Cun.$children[1].$el.style = isShow
            ? ''
            : 'display: none;';
          break;
        case '2cun':
          this.$refs.upload2Cun.$children[1].$el.style = isShow
            ? ''
            : 'display: none;';
          break;
      }
    },
    handleRemove(name) {
      this.dialogImageUrl = '';
      this.fileDic.delete(name);
      this.hideOrShowUpload(name, true);
    },
    handlePictureChange(file, fileList, name, refName) {
      const maxSize = 500 * 1024;
      if (file.size > maxSize) {
        this.$message.error('文件大小超过限制（500 KB）');
        // 清除文件列表，阻止文件上传
        this.$refs[refName].clearFiles();
        this.hideOrShowUpload(name, true);
      } else {
        // 文件大小符合限制，可以继续上传
        this.fileDic.set(name, file.raw);
        this.hideOrShowUpload(name, false);
      }
      // if (['id-front'].includes(name)) {
      //   var formData = new FormData();
      //   formData.append("headImg", file.raw);
      //   $.ajax({
      //     url: baseUrl + "studentInfo/headImgUpload",
      //     type: "POST",
      //     contentType: false,
      //     processData: false,
      //     data: formData,
      //     headers: {
      //       Authorization: JSON.parse(localStorage.getItem("userInfo")).token,
      //     },
      //     success: (data) => {
      //       console.log(`data`, data);
      //     },
      //   });
      // }
    },
    handlePicturePreview(file) {
      console.log(`fileList>>>>>`, this.fileList);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
});
